package me.leiusual.sharing.ui.mine

import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.fragment.app.activityViewModels
import androidx.fragment.app.viewModels
import androidx.lifecycle.ViewModelProvider
import androidx.navigation.fragment.findNavController
import androidx.navigation.fragment.navArgs
import androidx.recyclerview.widget.ItemTouchHelper
import androidx.recyclerview.widget.RecyclerView
import dagger.android.support.DaggerFragment
import kotlinx.android.synthetic.main.fragment_mine_address.*
import me.leiusual.sharing.R
import me.leiusual.sharing.repository.model.Data
import me.leiusual.sharing.ui.MainViewModel
import me.leiusual.sharing.ui.helper.HandleObserver
import me.leiusual.sharing.ui.helper.ItemTouchHelperCallbackImpl
import me.leiusual.sharing.ui.mine.adapter.MineAddressAdapter
import me.leiusual.sharing.ui.mine.adapter.MineAddressViewHolder
import me.leiusual.sharing.util.extension.requireValue
import me.leiusual.sharing.util.extension.toast
import timber.log.Timber
import javax.inject.Inject

/**
 * author: leiusual
 * create on: 2019-07-28
 * description:
 */
class MineAddressFragment : DaggerFragment(), View.OnClickListener {

  @Inject
  lateinit var factory: ViewModelProvider.Factory

  private val mainViewModel: MainViewModel by activityViewModels { factory }

  private val viewModel: MineAddressViewModel by viewModels { factory }

  private val args: MineAddressFragmentArgs by navArgs()

  override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
    return inflater.inflate(R.layout.fragment_mine_address, container, false)
  }

  override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
    super.onViewCreated(view, savedInstanceState)

    toolbar.setNavigationOnClickListener {
      findNavController().popBackStack()
    }

    recycler_view.adapter = MineAddressAdapter({ address ->
      Timber.v("点击：%s", address)

      if (args.selectable) {
        mainViewModel.address(address)
        findNavController().popBackStack()
      }
    }, { address ->
      Timber.v("编辑：%s", address)

      // 编辑
      val action = MineAddressFragmentDirections.actionMineAddressFragmentToMineAddressEditFragment(address)
      findNavController().navigate(action)
    })
    ItemTouchHelper(object : ItemTouchHelperCallbackImpl() {
      override fun onSwiped(viewHolder: RecyclerView.ViewHolder, direction: Int) {

        // 删除
        val mineAddressViewHolder = viewHolder as MineAddressViewHolder
        viewModel.addressDelete(mineAddressViewHolder.address.id)
      }
    }).attachToRecyclerView(recycler_view)

    button_new_address.setOnClickListener(this)

    observeData()
    viewModel.addressList(true)
  }

  private fun observeData() {
    viewModel.addressList.observe(viewLifecycleOwner, HandleObserver {
      Timber.v("addressList = %s", it)
      when (it) {
        is Data.Loading -> {
          if (viewModel.addressListFirst.requireValue) {
            state_constraint_layout.showProgress()
          }
        }
        is Data.Error -> {
          state_constraint_layout.showError(it.error.message)
        }
        is Data.Success -> {
          if (it.data.isNullOrEmpty()) {
            state_constraint_layout.showEmpty()
          } else {
            state_constraint_layout.showContent()

            val adapter = recycler_view.adapter as MineAddressAdapter
            adapter.submitList(it.data)
          }
        }
      }
    })

    viewModel.addressDelete.observe(viewLifecycleOwner, HandleObserver {
      Timber.v("addressDelete = %s", it)
      when (it) {
        is Data.Loading -> {
          // ignore
        }
        is Data.Error -> {
          toast("删除失败")
          recycler_view.adapter?.notifyDataSetChanged()
        }
        is Data.Success -> {
          toast("删除成功")
          viewModel.addressList(false)
        }
      }
    })
  }

  override fun onClick(v: View?) {
    when (v?.id) {
      R.id.button_new_address -> {
        findNavController().navigate(R.id.action_mineAddressFragment_to_mineAddressEditFragment)
      }
    }
  }
}